package com.paishen.peiniwan.module.profile;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.dialog.SelectionDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.AuthInfoDao;

import com.paishen.peiniwan.database.util.ModelConverter;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.AuthInfo;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.squareup.okhttp.Request;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by Administrator on 2015/12/1.
 */
public class MainProfileAuthLayout extends LinearLayout {

    private final AuthInfoDao authInfoDao;
    private com.paishen.peiniwan.database.AuthInfo dbAuthInfo;
    private String urlAuthAvatar;
    private final ImageView imgNewAuthAvatar;
    private final View layPart1, layPart2;
    private final ImageView imgAuthStatus;

    public MainProfileAuthLayout(Context context) {
        this(context, null);
    }

    public MainProfileAuthLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // interrupt click event
            }
        });

        LayoutInflater.from(context).inflate(R.layout.layout_main_profile_auth, this);
        // ((ViewGroup)getChildAt(0)).getChildAt(0).setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);
        setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);
        imgNewAuthAvatar = (ImageView) findViewById(R.id.img_new_auth);
        imgAuthStatus = (ImageView) findViewById(R.id.img_auth_status);

        layPart1 = findViewById(R.id.lay_part_1);
        layPart2 = findViewById(R.id.lay_part_2);

        String[] profileValidStatus = getResources().getStringArray(R.array.profile_auth_status_value);
        authInfoDao = App.i().getCurrDaoSession().getAuthInfoDao();
        dbAuthInfo = authInfoDao.queryBuilder().where(AuthInfoDao.Properties.UserId.eq(App.i().getUser().getId())).unique();

        findViewById(R.id.lay_new_auth).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showGetPhotoDialog();
            }
        });
        findViewById(R.id.btn_start).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                requestUserValidApplication();
            }
        });

        if (TextUtils.equals(dbAuthInfo.getStatus(), profileValidStatus[0])
                || TextUtils.equals(dbAuthInfo.getStatus(), profileValidStatus[1])) {
            layPart1.setVisibility(View.VISIBLE);
            layPart2.setVisibility(View.GONE);
        } else if (TextUtils.equals(dbAuthInfo.getStatus(), profileValidStatus[2])
                || TextUtils.equals(dbAuthInfo.getStatus(), profileValidStatus[3])) {
            layPart2.setVisibility(View.VISIBLE);
            layPart1.setVisibility(View.GONE);

            ImageView imgAvatar = (ImageView) findViewById(R.id.img_avatar);
            Glide.with(getContext()).load(App.i().getUser().getHead_img_url()).centerCrop().into(imgAvatar);
            ImageView imgAuth = (ImageView) findViewById(R.id.img_auth);
            Glide.with(getContext()).load(dbAuthInfo.getReal_photo()).centerCrop().into(imgAuth);

            if (TextUtils.equals(dbAuthInfo.getStatus(), profileValidStatus[1])) {
                imgAuthStatus.setImageResource(R.mipmap.main_profile_auth_ing);
            } else if (TextUtils.equals(dbAuthInfo.getStatus(), profileValidStatus[2])) {
                imgAuthStatus.setImageResource(R.mipmap.main_profile_auth_success);
            } else if (TextUtils.equals(dbAuthInfo.getStatus(), profileValidStatus[3])) {
                imgAuthStatus.setImageResource(R.mipmap.main_profile_auth_fail);

                String failNote = dbAuthInfo.getNote();
                if (TextUtils.isEmpty(failNote)) failNote = App.i().getString(R.string.auth_fail);
                findViewById(R.id.lay_auth_fail).setVisibility(View.VISIBLE);
                TextView txAuthFailNote = (TextView) findViewById(R.id.tx_auth_fail_note);
                txAuthFailNote.setText(failNote);
                findViewById(R.id.btn_reauth).setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        layPart2.setVisibility(View.GONE);
                        layPart1.setVisibility(View.VISIBLE);
                    }
                });
            }
        }
    }

    public final void requestUserValidApplication() {
        if (TextUtils.isEmpty(urlAuthAvatar)) {
            BaseUtil.showToast(R.string.auth_new_title);
            return;
        }

        final LoadingDialog dlgLoading = new LoadingDialog.Builder(getContext()).create();
        dlgLoading.show();
        File real_photo = new File(urlAuthAvatar);
        PnwHttpManager.User.validApplication(((BaseActivity) getContext()).TAG, real_photo, new PnwOkCallbackAdapter<HttpRespData<AuthInfo>>() {
            @Override
            public void onResponse(HttpRespData<AuthInfo> response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    dbAuthInfo = ModelConverter.mergeOrReplace(dbAuthInfo, response.data, App.i().getUser().getId());
                    authInfoDao.insertOrReplace(dbAuthInfo);

                    EventBus.getDefault().post(new BusEvent( BusEvent.ACTION_MAIN_PROFILE_AUTH_SUBMIT));
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }


    public void setUserAvatar(String filePath) {
        this.urlAuthAvatar = filePath;
        Glide.with(getContext()).load(filePath).into(imgNewAuthAvatar);
    }

    private SelectionDialog dlgGetPhoto;

    private void showGetPhotoDialog() {
        if (dlgGetPhoto == null) {
            List<SelectionDialog.Menu> menuList = new ArrayList<>();
            menuList.add(new SelectionDialog.Menu(getContext().getString(R.string.frame_photo_from_camera), new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getContext() instanceof BaseActivity) {
                        BaseActivity activity = (BaseActivity) getContext();
                        activity.openCamera();
                        dlgGetPhoto.dismiss();
                    }
                }
            }));

            menuList.add(new SelectionDialog.Menu(getContext().getString(R.string.frame_photo_from_album), new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getContext() instanceof BaseActivity) {
                        BaseActivity activity = (BaseActivity) getContext();
                        activity.openPhotos();
                        dlgGetPhoto.dismiss();
                    }
                }
            }));
            SelectionDialog.Builder builder = new SelectionDialog.Builder(getContext());
            dlgGetPhoto = builder.setMenuList(menuList).create();
        }
        dlgGetPhoto.show();
    }
}
